package com.lanou.dllo.baisibudejie.adapater;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Movie;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.lanou.dllo.baisibudejie.R;
import com.lanou.dllo.baisibudejie.entity.ImageEntity;
import com.lanou.dllo.baisibudejie.view.CircleImage;
import com.lanou.dllo.baisibudejie.view.GifMovieView;
import com.lanou.dllo.baisibudejie.volley.StreamRequest;
import com.lanou.dllo.baisibudejie.volley.VolleySingleton;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/23.
 */
public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.JokesViewHolder> {

    private Context context;
    private List<ImageEntity> datas;
    private RequestQueue queue;

    public ImagesAdapter(Context c) {
        this.context = c;
        queue = Volley.newRequestQueue(c);
    }

    /**
     * 加载行布局
     *
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public JokesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.card_images_item, null);

        return new JokesViewHolder(view);
    }

    /**
     * 解析数据设置内容
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(JokesViewHolder holder, int position) {

        ImageEntity listEntity = datas.get(position);
        if (listEntity != null) {


            if (listEntity.getText() != null && listEntity.getText().length() > 0) {
                holder.images_item_contentTv.setText(listEntity.getText());//设置内容
            }
            if (listEntity.getName() != null && listEntity.getName().length() > 0) {
                holder.images_item_nameTv.setText(listEntity.getName());//设置姓名
            }
            if (listEntity.getCreated_at() != null && listEntity.getCreated_at().length() > 0) {
                holder.images_item_timeTv.setText(listEntity.getCreated_at());//设置时间
            }
            if (listEntity.getLove() != null && listEntity.getLove().length() > 0) {
                holder.images_item_loveTv.setText(listEntity.getLove());//点赞
            } else {
                holder.images_item_loveTv.setText(0);
            }
            if (listEntity.getHate() != null && listEntity.getHate().length() > 0) {
                holder.images_item_hateTv.setText(listEntity.getHate());//踩
            } else {
                holder.images_item_hateTv.setText(0);
            }
            if (listEntity.getProfile_image() != null && listEntity.getProfile_image().length() > 0) {
                getCircleBitmap(listEntity.getProfile_image(), holder.images_item_headIconIv);//头像
            }

            if (listEntity.getImage0() != null && listEntity.getImage0().length() > 0) {
//                int width = Integer.parseInt(listEntity.getWidth());
//                int height = Integer.parseInt(listEntity.getHeight());
//                holder.images_item_imageIv.setMaxWidth(width);
//                holder.images_item_imageIv.setMaxHeight(height);
                //判断是否是动态图
                if (listEntity.getIs_gif().equals("1")) {
                    holder.images_item_imageIv.setVisibility(View.GONE);
                    holder.images_item_imageGm.setVisibility(View.VISIBLE);
//                   FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.images_item_imageGm.getLayoutParams();
//                    params.width = Integer.parseInt(listEntity.getWidth());
//                    params.height = Integer.parseInt(listEntity.getHeight());
//                    holder.images_item_imageGm.setLayoutParams(params);

                    getGifMovie(listEntity.getImage0(), holder.images_item_imageGm);

                } else if (listEntity.getIs_gif().equals("0")) {
                    holder.images_item_imageGm.setVisibility(View.GONE);
                    holder.images_item_imageIv.setVisibility(View.VISIBLE);
                    getBitmap(listEntity.getImage0(), holder.images_item_imageIv);

                }


            }
            if (listEntity.getRepost() != null && listEntity.getRepost().length() > 0) {
                holder.images_item_repostTv.setText(listEntity.getRepost());//分享数量
            } else {
                holder.images_item_repostTv.setText(0);
            }
            if (listEntity.getComment() != null && listEntity.getComment().length() > 0) {
                holder.images_item_commentTv.setText(listEntity.getComment());//评论数量
            } else {
                holder.images_item_commentTv.setText(0);
            }


        }

    }

    @Override
    public int getItemCount() {
        return datas != null && datas.size() > 0 ? datas.size() : 0;
    }

    /**
     * 组件缓存内部类
     */
    class JokesViewHolder extends RecyclerView.ViewHolder {

        private TextView images_item_contentTv;//内容
        private TextView images_item_nameTv;//姓名
        private TextView images_item_timeTv;//时间
        private TextView images_item_loveTv;//点赞量
        private TextView images_item_hateTv;//踩量
        private ImageView images_item_headIconIv;//头像
        private TextView images_item_repostTv;//转发量
        private TextView images_item_commentTv;//评论量
        private GifMovieView images_item_imageGm;//动态图片
        private NetworkImageView images_item_imageIv;//图片

        public JokesViewHolder(View v) {
            super(v);
            images_item_contentTv = (TextView) v.findViewById(R.id.images_item_contentTv);
            images_item_nameTv = (TextView) v.findViewById(R.id.images_item_nameTv);
            images_item_timeTv = (TextView) v.findViewById(R.id.images_item_timeTv);
            images_item_loveTv = (TextView) v.findViewById(R.id.images_item_loveTv);
            images_item_hateTv = (TextView) v.findViewById(R.id.images_item_hateTv);
            images_item_headIconIv = (ImageView) v.findViewById(R.id.images_item_headIconIv);
            images_item_repostTv = (TextView) v.findViewById(R.id.images_item_repostTv);
            images_item_commentTv = (TextView) v.findViewById(R.id.images_item_commentTv);
            images_item_imageGm = (GifMovieView) v.findViewById(R.id.images_item_imageGm);
            images_item_imageIv = (NetworkImageView) v.findViewById(R.id.images_item_imageIv);
        }

    }

    public void addData(List<ImageEntity> data) {
        this.datas = data;
        notifyDataSetChanged();//数据改变 页面刷新
    }

    //设置圆形图片
    private void getCircleBitmap(String url, final ImageView imageView) {

        ImageRequest request = new ImageRequest(url,
                new Response.Listener<Bitmap>() {

                    @Override
                    public void onResponse(Bitmap response) {
                        int radius;
                        // 将返回的bitmap图片对象设置到图片组件中
                        if (response.getWidth() <= response.getHeight()) {
                            radius = response.getWidth() / 2;
                        } else {
                            radius = response.getHeight() / 2;
                        }

                        Bitmap circleImage = new CircleImage(context).getCroppedRoundBitmap(response, radius);
                        imageView.setImageBitmap(circleImage);
                    }
                },
                0, 0, Bitmap.Config.ARGB_8888,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                        error.printStackTrace();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);//将本次图片请求加入到请求队列中
    }

    //设置NetworkImage
    private void getBitmap(String url, final NetworkImageView networkImageView) {
        ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
        networkImageView.setDefaultImageResId(R.mipmap.cleak_repeat_normal);
        networkImageView.setErrorImageResId(R.mipmap.cleak_repeat_normal);
        networkImageView.setImageUrl(url, imageLoader);


    }


    //设置动态图
    private void getGifMovie(String url, final GifMovieView imageView) {

        StreamRequest request = new StreamRequest(url,
                new Response.Listener<InputStream>() {
                    @Override
                    public void onResponse(InputStream response) {
                        Movie movie = Movie.decodeStream(response);
                        imageView.setMovie(movie);
                        try {
                            response.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };


        queue.add(request);//将本次图片请求加入到请求队列中
    }
}
